#!/usr/bin/ruby
#encoding : utf-8
#
# 该程序为容器的一部分,所有的源码都将通过该脚本运行并返回
# 例子
#   run.rb php
# 启动docker的例子
#   docker run -i -t moli/run ruby ~/run.rb php PD9waHAKZWNobyAiaGVsbG8gd29ybGQiOwo/Pg==

if ARGV.length < 2
  puts "参数需要 程序语言，程序代码(base64编码后的代码)，例如: run.rb php base64(\"echo 'hello'\")"
  exit 1
end

# 将代码写入文件
def write_code_to_file(filename, code)
  file = nil
  begin
    file = File.new filename, "w"
    file.write code
  ensure
    file.close if file
  end
end

require 'base64'

lang = ARGV.shift.to_s.downcase
code =  Base64.decode64 ARGV.shift
params = ARGV.shift

PHP = "php"
RUBY = "ruby"
PYTHON = "python"
JAVA = "java"
C = "c"
CPP = "cpp"
GO = "go"

PATH = "./" # 代码临时执行目录


result =
case lang
  when PHP
    filename = PATH + "temp.php"
    write_code_to_file filename, code
    `php -f #{filename}`
  when RUBY
    filename = PATH + "temp.rb"
    write_code_to_file filename, code
    `ruby #{filename}`
  when PYTHON
    filename = PATH + "temp.py"
    write_code_to_file filename, code
    `python #{filename}`
  when JAVA
    if params.nil?
      "请传入java类名称."
    else
      filename = PATH + params +".java"
      write_code_to_file filename, code
      `javac #{filename}`
      `java #{params}`
    end
  when C
    filename = PATH + "temp.c"
    write_code_to_file filename, code
    `gcc #{filename} -o temp`
    `#{PATH}c`
  when CPP
    filename  = PATH + "temp.cpp"
    write_code_to_file filename, code
    `g++ #{filename} -o temp`
    `#{PATH}cpp`
  when GO
    filename = PATH + "temp.go"
    write_code_to_file filename, code
    `go run #{filename}`
end

puts result